﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using MasterDetailTemplate.Models;
using Newtonsoft.Json;
using Xamarin.Essentials;

namespace MasterDetailTemplate.Services.impl
{
    public class HealthInfoService : IHealthInfoService
    {

        /// <summary>
        /// 服务器常量名--用于提示错误信息
        /// </summary>
        public const string TianxingServer = "每日健康资讯";

        /// <summary>
        /// httpClient
        /// </summary>
        private HttpClient _httpClient = new HttpClient();

        /// <summary>
        /// alertService
        /// </summary>
        private IAlertService _alertService = new AlertService();

        /// <summary>
        /// 访问API获取健康资讯信息
        /// </summary>
        /// <returns></returns>
        public async Task<HealthInfo> GetHealthInfoAsync()
        {
            HttpResponseMessage response;
            try
            {
                response = await _httpClient.GetAsync(
                    "https://api.tianapi.com/health/index?key=88284cf993d93c0a1bdf330d1ab402e2&num=1");

            }
            catch (Exception e)
            {
                _alertService.ShowAlert(
                    ErrorMessages.HTTP_CLIENT_ERROR_TITLE,
                    ErrorMessages.HttpClientErrorMessage(TianxingServer, e.Message),
                    ErrorMessages.HTTP_CLIENT_ERROR_BUTTON);
                return null;
            }
            var json = await response.Content.ReadAsStringAsync();
            var root = JsonConvert.DeserializeObject<Root>(json);
            return new HealthInfo()
            {
                Title = root.newslist[0].title,
                Description = root.newslist[0].description,
                PicUrl = root.newslist[0].picUrl,
                Url = root.newslist[0].url
            };
        }

        /// <summary>
        /// 打开显示详情网址。
        /// </summary>
        /// <param name="url">网址</param>
        public async Task OpenAsync(string url)
        {
            await Browser.OpenAsync(url, BrowserLaunchMode.SystemPreferred);
        }
    }



    /// <summary>
    /// json反序列化所使用的类
    /// </summary>
    public class Newslist
    {
        public string id { get; set; }
        public string title { get; set; }
        public string description { get; set; }
        public string picUrl { get; set; }
        public string url { get; set; }
    }

    public class Root
    {
        public List<Newslist> newslist { get; set; }
    }
}
